package com.softme.trade.control.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import com.softme.trade.model.Firm;
import com.softme.trade.model.dao.FirmDAO;
import com.softme.trade.util.BeanFactory;

@FacesConverter(value = "firmConverter", forClass = Firm.class)
public class FirmConverter implements Converter
{

	private FirmDAO dao;

	@Override
	public Object getAsObject(FacesContext context, UIComponent comp, String value)
	{
		String firmName = value.split(" - ")[1];
		
		return this.getFirmDAO().findByName(firmName);
	}

	@Override
	public String getAsString(FacesContext context, UIComponent comp, Object obj)
	{
		Firm firm = (Firm) obj; 
		return firm.getAcronym() + " - " + firm.getName();
	}

	private FirmDAO getFirmDAO()
	{
		if (this.dao == null || this.dao.getHibernateTemplate() == null)
			this.dao = (FirmDAO) BeanFactory.getBean("firmDAO", FirmDAO.class);

		return this.dao;
	}

}
